#pragma once
#include <iostream>
#include "Log.hpp"
#include <sys/epoll.h>
#include "common.hpp"

class Epoller
{
  private:
   bool EventMethodCore(int fd, uint32_t events, int type)
   {
        //添加对于fd的event事件的关心
        struct epoll_event ev;
        ev.events = events;
        ev.data.fd = fd;
        int n = epoll_ctl(_epfd,type,fd,&ev);
        if(n<0)
        {
            Log(ERROR,"epoll_ctl error!");
            return false;
        }
        Log(DEBUG,"epoll_ctl success,epfd:%d",_epfd);
        return true;
   }

  public:
    Epoller()
    {
        //创建epfd
        _epfd = epoll_create(128);//size不重要
        if(_epfd<0)
        {
            Log(FATAL,"epoll_create error!");
            exit(EPOLL_CREATE_ERROR);
        }
        //成功创建了epfd
        Log(DEBUG,"epoll_create success,epfd:%d",_epfd);
    }

    ~Epoller()
    {
        if(_epfd>=0)
            close(_epfd);
    }

    bool AddEvent(int fd, uint32_t event)
    {
        return EventMethodCore(fd,event,EPOLL_CTL_ADD);
    }

    bool ModEvent(int fd, uint32_t events)
    {
        return EventMethodCore(fd,events,EPOLL_CTL_MOD);
    }

    bool DelEvent(int fd)
    {
        return epoll_ctl(_epfd,EPOLL_CTL_DEL,fd,nullptr);
    }

    int Wait(struct epoll_event revs[], int num, int timeout)
    {       
        
        return epoll_wait(_epfd,revs,num,timeout);
    }



  private:  
    int _epfd;
};